package com.ocom.payhandle.controller;


import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.card.EntityXfDeviceInfo;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.RespUtilMach;
import com.ocom.payhandle.service.DeviceInfoService;
import com.ocom.payhandle.service.UpgradePlanService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class DeviceStateController {

    @Autowired
    private DeviceInfoService deviceInfoService;


    @Autowired
    private UpgradePlanService upgradePlanService;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 获取设备同步信息标志（getDeviceFlag）
     * */
    @GetMapping(PayHandleUrl.URL_PayHandle_GetDeviceFlag)
    public RespMachMessage GetDeviceFlag(Long companyId, String machNo, String versionCode){
        if (companyId == null){
            log.error("单位编号为空");
            return RespUtilMach.error(MachEnum.AUTH_ERROR);
        }
        if (machNo.isEmpty()){
            log.error("单位编号为空");
            return RespUtilMach.error(MachEnum.AUTH_ERROR);
        }

        // 从设备信息表mj_device_info找到com_id ，device_no匹配的记录
        EntityXfDeviceInfo entityDeviceInfo = deviceInfoService.GetDeviceInfo(companyId, machNo);
        if (entityDeviceInfo == null){
            log.error("设备无数据或当前位置无记录");
            return RespUtilMach.error(MachEnum.MACH_NOT_MSG);
        }
        //1.修改数据库：xf_device_info . comm_time=当前系统时间
        try {
//            log.info("更新最后通信时间");
            if(redisUtil.get("HttpMachCommTime:"+machNo)==null){
                deviceInfoService.UpdateCommTime(companyId,machNo);
            }
            redisUtil.set("HttpMachCommTime:"+machNo,new Date(),15000l);
//            deviceInfoService.UpdateCommTime(companyId,machNo);
        }catch (Exception exception){
            log.error("更新最后通信时间失败"+exception.getMessage());
            return RespUtilMach.error(MachEnum.NOT_COMMTIME_COMMMODE);
        }

        //1.如果versionCode 不为空且不等于xf_device_info . app_ver：修改app_ver
        //更新数据
        if (!versionCode.isEmpty() && !versionCode.equals(entityDeviceInfo.getAppVer())){
            try {
                log.info("更新设备当前版本（设备上报）信息");
                deviceInfoService.updateAppVer(entityDeviceInfo.getComId(), entityDeviceInfo.getDeviceNo(), versionCode);
            }catch (Exception exception){
                log.error("更新设备当前版本（设备上报）失败"+exception.getMessage());
                return RespUtilMach.error(MachEnum.NOT_APPVER);
            }
        }



        // 2.paramUpdate = xf_device_info . para_state == mj_device_info . 0 ? 0 : 1
        Integer paramUpdate = 0;
        if (entityDeviceInfo.getParaState()==null){
            paramUpdate = 0;
        }else {
            paramUpdate = entityDeviceInfo.getParaState();
        }
        Integer fkUpdate = entityDeviceInfo.getFkparaState()==0?0:1;
        Integer listUpdate = 0;
        if (entityDeviceInfo.getListState()==1 || entityDeviceInfo.getListState()==2){
           listUpdate = 1;
        }

        Integer zhxySecret = 0;
        Map<String,Object> map = new HashMap<>();

        //菜单更新标识
        Integer menuUpdate = 0 ;
        if(entityDeviceInfo.getMenuState()==1){
            menuUpdate=1;
        }

        if (entityDeviceInfo.getRsaState()!=null && entityDeviceInfo.getRsaState()==1){
            zhxySecret = 1;
        }

        map.put("fkUpdate",fkUpdate);
        map.put("paramUpdate",paramUpdate);
        map.put("zhxySecret",zhxySecret);
        map.put("listUpdate",listUpdate);
        map.put("meal",0);
        map.put("menu",menuUpdate);


        map.put("version","prod");
        String version = "";
        try{
            version = upgradePlanService.getScaleUpgradeStatus(companyId,"payhandle");
            map.put("version", version);
        }catch (Exception e){
            log.error("获取消费操作版本异常【{}】【{}】",machNo,e);
        }
//        log.info("获取消费操作版本【{}】【{}】",machNo,version);
        return RespUtilMach.success(map);


    }


    @PostMapping(PayHandleUrl.URL_PayHandle_updateXFDeviceInfo2)
    public RespMachMessage updateXFDeviceInfo2(Long companyId, Integer  listState, String deviceNo){

        deviceInfoService.updateXFDeviceInfo2(companyId, listState, deviceNo);
        return RespUtilMach.success();
    }

}
